using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace Media_Renamer {
    public partial class ObtainInfoFilename : LocalizedForm {
        MP3File[] _files;
        public ObtainInfoFilename() {
            InitializeComponent();
            setUpCulture();
        }
        override public void setUpCulture() {
            this.tabBasic.Text = this.getString("obtainInfoFilename.tabs.basic");
            this.tabAdvanced.Text = this.getString("obtainInfoFilename.tabs.advanced");
            this.btnCancel.Text = this.getString("obtainInfoFilename.buttonCancel");
            this.btnSave.Text = this.getString("obtainInfoFilename.buttonSave");
            this.Text = this.getString("obtainInfoFilename.title");
            /*BASIC */
            this.btnBasicPreview.Text = this.getString("obtainInfoFilename.tabs.basic.buttonPreview");
            this.lblBasicPattern.Text = this.getString("obtainInfoFilename.tabs.basic.pathFormatLabel");
            this.lblBasicHelp.Text = this.getString("obtainInfoFilename.tabs.basic.help");

            /*Advanced */

            this.lblAdvPattern.Text = this.getString("obtainInfoFilename.tabs.advanced.patternLabel");
            this.grpAdvMatches.Text = this.getString("obtainInfoFilename.tabs.advanced.matchesGroup");
            this.btnAdvAddMatch.Text = this.getString("obtainInfoFilename.tabs.advanced.matchesGroup.addButton");
            this.btnAdvRemoveMatch.Text = this.getString("obtainInfoFilename.tabs.advanced.matchesGroup.removeButton");
            this.grpAdvSource.Text = this.getString("obtainInfoFilename.tabs.advanced.sources");
            this.rbtnAdvAlbum.Text = this.getString("obtainInfoFilename.tabs.advanced.sources.album");
            this.rbtnAdvArtist.Text = this.getString("obtainInfoFilename.tabs.advanced.sources.artist");
            this.rbtnAdvComments.Text = this.getString("obtainInfoFilename.tabs.advanced.sources.comments");
            this.rbtnAdvFilename.Text = this.getString("obtainInfoFilename.tabs.advanced.sources.filename");
            this.rbtnAdvFilePath.Text = this.getString("obtainInfoFilename.tabs.advanced.sources.filepath");
            this.rbtnAdvTitle.Text = this.getString("obtainInfoFilename.tabs.advanced.sources.title");
            this.btnAdvancedPreview.Text = this.getString("obtainInfoFilename.tabs.advanced.previewButton");

            string[] items = {
                this.getString("mediaLibrary.album"),
                this.getString("mediaLibrary.artist"),
                this.getString("mediaLibrary.title"),
                this.getString("mediaLibrary.comment"),
                this.getString("mediaLibrary.year"),
                this.getString("mediaLibrary.trackNumber")
            };
            this.cmbAdvMatches.Items.Clear();
            this.cmbAdvMatches.Items.AddRange(items);
            
        }
        public MP3File[] Files {
            get { return _files;}
            set {
                _files = new MP3File[value.Length];
                mediaLibrary1.clear();
                int index = 0;
                foreach (MP3File file in value) {
                    MP3File newFile = new MP3File(file.filePath);
                    mediaLibrary1.addFile(newFile);
                    _files[index] = newFile;
                    index++;
                }
            }
        }

        private void btnPreview_Click(object sender, EventArgs e) {
            //%trackNo% - %title%.mp3
            //([a-zA-Z]+) -([0-9]+)-([0-9]+).mp3
            Properties.Settings.Default.ObtainInfo_PatternBasic = this.txtBasicPattern.Text;
            Properties.Settings.Default.Save();
            String regexString = Regex.Escape(this.txtBasicPattern.Text);
            regexString = getParsedString(regexString);
            //CustomMessageBox.Show("Regex: " + regexString);
            Regex reg = new Regex(regexString);
            List<String> tags = getTags(this.txtBasicPattern.Text);
            foreach (MP3File file in _files) {
                String source = file.filename;
                MatchCollection matches = reg.Matches(source);
                foreach (Match m in matches) {
                    //CustomMessageBox.Show("Matched: " + m.Value);
                    int groupIndex = 0;
                    foreach (Group g in m.Groups) {
                        if (groupIndex > 0) {
                            String tag = tags[groupIndex-1];
                            if (tag == "%artist%") {
                                file.Id3v2Tag.Artist = g.Value;
                            } else if (tag == "%album%") {
                                file.Id3v2Tag.Album= g.Value;
                            } else if (tag == "%title%") {
                                file.Id3v2Tag.Title = g.Value;
                            } else if (tag == "%genre%") {
                                file.Id3v2Tag.Genre= g.Value;
                            } else if (tag == "%comment%") {
                                //file.Id3v2Tag.Commentslist= g.Value;
                            } else if (tag == "%year%") {
                                file.Id3v2Tag.Year = g.Value;
                            } else if (tag == "%trackNo%") {
                                file.Id3v2Tag.TrackNumber = g.Value;
                            }
                        }
                        //CustomMessageBox.Show("Grupo " + groupIndex + ": " + g.Value);
                        groupIndex++;
                    }
                }
                this.mediaLibrary1.refreshGrid();


            }

            
        }
        private string getParsedString(String text) {
            //title, album, artist, genre
            text = text.Replace("%artist%", "([\\'\\(\\)\\-\\,\\w\\s]*)");
            text = text.Replace("%album%", "([\\'\\(\\)\\-\\,\\w\\s]*)");
            text = text.Replace("%title%", "([\\'\\(\\)\\-\\,\\w\\s]*)");
            text = text.Replace("%genre%", "([\\'\\(\\)\\-\\,\\w\\s]*)");
            text = text.Replace("%comment%", "([\\'\\(\\)\\-\\,\\w\\s]*)");
            text = text.Replace("%year%", "([\\d]*)");
            text = text.Replace("%trackNo%", "([\\d]*)");
            return text;
        }
        private List<String> getTags(String pattern) {
            
            List<String> tags = new List<String>();
            String regexString = "(%artist%)|(%album%)|(%title%)|(%genre%)|(%comment%)|(%year%)|(%trackNo%)*";
            Regex reg = new Regex(regexString);
            MatchCollection matches = reg.Matches(pattern);
            foreach (Match m in matches) {
                int groupIndex = 0;
                foreach (Group g in m.Groups) {
                    if (groupIndex > 0 & g.Success) {
                        tags.Add(g.Value);
                    }
                    groupIndex++;
                    
                }
                
            }
            return tags;
        }

        private void btnSave_Click(object sender, EventArgs e) {
            setButtonsEnabled(false);
            if (tabControl1.SelectedTab == this.tabBasic) {
                this.barProgress.Visible = true;
                this.barProgress.Maximum = _files.Length;
                foreach (MP3File file in _files) {
                    file.saveInfo();
                    this.barProgress.Value += 1; 
                    Application.DoEvents();
                }
            }
            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        private void btnCancel_Click(object sender, EventArgs e) {
            this.DialogResult = DialogResult.Cancel;
        }
        private void setButtonsEnabled(Boolean enabled) {
            this.btnCancel.Enabled = enabled;
            this.btnSave.Enabled = enabled;
        }

        private void btnAdvancedPreview_Click(object sender, EventArgs e) {
            //Properties.Settings.Default.ObtainInfo_PatternAdvanced= this.txtAdvPattern.Text;
           // Properties.Settings.Default.Save();
            Regex reg = new Regex(this.txtAdvPattern.Text);
            //List<String> tags = getTags(this.txtAdvPattern.Text);
            foreach (MP3File file in _files) {
                String source = file.filename;
                if (rbtnAdvAlbum.Checked) source = file.Id3v2Tag.Album;
                if (rbtnAdvArtist.Checked) source = file.Id3v2Tag.Artist;
                if (rbtnAdvComments.Checked) source = "";
                if (rbtnAdvFilename.Checked) source = file.filename;
                if (rbtnAdvFilePath.Checked) source = file.filePath;
                if (rbtnAdvTitle.Checked) source = file.Id3v2Tag.Title;

                MatchCollection matches = reg.Matches(source);
                foreach (Match m in matches) {
                    //CustomMessageBox.Show("Matched: " + m.Value);
                    int groupIndex = 0;
                    foreach (Group g in m.Groups) {
                        if (groupIndex > 0 && groupIndex <= lstAdvMatches.Items.Count) {
                            String tag = (String)lstAdvMatches.Items[groupIndex - 1];
                            int separator = tag.IndexOf("~");
                            if (separator > -1) {
                                tag = tag.Substring(separator+1);
                                if (tag == this.getString("mediaLibrary.artist")) {
                                    file.Id3v2Tag.Artist = g.Value;
                                } else if (tag == this.getString("mediaLibrary.album")) {
                                    file.Id3v2Tag.Album = g.Value;
                                } else if (tag == this.getString("mediaLibrary.title")) {
                                    file.Id3v2Tag.Title = g.Value;
                                } else if (tag == this.getString("mediaLibrary.genre")) {
                                    file.Id3v2Tag.Genre = g.Value;
                                } else if (tag == this.getString("mediaLibrary.comment")) {
                                    //file.Id3v2Tag.Commentslist= g.Value;
                                } else if (tag == this.getString("mediaLibrary.year")) {
                                    file.Id3v2Tag.Year = g.Value;
                                } else if (tag == this.getString("mediaLibrary.trackNumber")) {
                                    file.Id3v2Tag.TrackNumber = g.Value;
                                }
                            }
                        }
                        //CustomMessageBox.Show("Grupo " + groupIndex + ": " + g.Value);
                        groupIndex++;
                    }
                }
                this.mediaLibrary1.refreshGrid();


            }
        }

        private void lstAdvMatches_SelectedIndexChanged(object sender, EventArgs e) {
            if (this.lstAdvMatches.SelectedIndex > -1) {
                this.cmbAdvMatches.Enabled = true;
                this.btnAdvRemoveMatch.Enabled = true;
                String tag = (String)lstAdvMatches.SelectedItem;
                int separator = tag.IndexOf("~");
                if (separator > -1) {
                    tag = tag.Substring(separator + 1);
                } else { tag = ""; }
                int index = this.cmbAdvMatches.Items.IndexOf(tag);
                this.cmbAdvMatches.SelectedIndex = index;
            } else {
                this.cmbAdvMatches.Enabled = false;
                this.btnAdvRemoveMatch.Enabled =false;
            }
        }

        private void cmbAdvMatches_SelectedIndexChanged(object sender, EventArgs e) {
            int selected = this.lstAdvMatches.SelectedIndex;
            this.lstAdvMatches.Items[selected] = (selected + 1) + "~" + (String)this.cmbAdvMatches.SelectedItem;
        }

        private void btnAdvAddMatch_Click(object sender, EventArgs e) {
            this.lstAdvMatches.Items.Add("1~");
        }
    }
}